package com.itheima.travel.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.res.GetwayRespons;
import com.itheima.travel.session.SubjectUserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

//是否拦截
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private SubjectUserContext subjectUserContext;

    //之前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //判断用户是否为登录状态
        boolean isLogin = subjectUserContext.existSubject();
        if(!isLogin){
            //不是登录状态
            //响应状态码
            GetwayRespons getwayRespons = GetwayRespons.builder().
                    code(StatusEnum.NO_LOGIN.getCode()).
                    msg(StatusEnum.NO_LOGIN.getMsg()).
                    data("").
                    operationTime(new Date()).
                    build();
            //将对象转为json响应回去
            response.setContentType("application/json; charset=utf-8");
            //转换为json,且处理时间格式
            response.getWriter().write(JSONObject.toJSONString(getwayRespons, SerializerFeature.WriteDateUseDateFormat));
            return false;
        }
        return true;
    }
}
